<template>
    <div class="tree-box">
        <div class="top flex">
            <el-input v-model="searchKey" placeholder="支持ID、名称模糊搜索" class="search-input" @keyup.enter="search">
                <template #append>
                    <el-icon :size="16" @click="search"><MyIcon name="search"></MyIcon></el-icon>
                </template>
            </el-input>
            <el-button class="icon-button" @click="addNode">
                <el-icon :size="16"><MyIcon name="plus"></MyIcon></el-icon>
            </el-button>
            <el-button class="icon-button">
                <el-icon :size="16"><MyIcon name="download"></MyIcon></el-icon>
            </el-button>
        </div>
        <MyProductTree ref="myProductTree" :data="treeData" :props="{ filterNodeMethod: filterNode, defaultExpandedKeys }" @select="selectNode"></MyProductTree>
        <MyCategoryFormDialog ref="myCategoryFormDialog" @complete="addNodeComplete"></MyCategoryFormDialog>
    </div>
</template>

<script setup lang="ts">
import MyCategoryFormDialog from './CategoryFormDialog.vue';
const emits = defineEmits<{
    (event: 'select', data: any, node: any): void;
}>();

const searchKey = ref('');
const myProductTree = ref<MyComment.ProductTreeInstance>();
const search = () => {
    myProductTree.value?.filter(searchKey.value);
};

const myCategoryFormDialog = ref();
const addNode = () => {
    if (currentNodeData.value.level === 2) {
        myCategoryFormDialog.value?.open(false, currentNodeData.value?.id || '');
    }
};

const addNodeComplete = (result: boolean) => {
    if (result) {
        defaultExpandedKeys.value = [currentNodeData.value.id];
        getData();
    }
};

const treeData = ref<MyComment.ProductTreeData[]>([]);

const currentNodeData = ref();

const defaultExpandedKeys = ref<string[]>([]);

const filterNode = (value: string, data: any) => {
    if (!value) return true;
    return data.name.includes(value);
};

const selectNode = (data: any, node: any) => {
    currentNodeData.value = data;
    emits('select', data, node);
};

const getData = async () => {
    const res = await MyService.product.getCategoryTree({ searchKey: searchKey.value });
    if (res.code === 200) {
        treeData.value = res.data;
    }
};

const init = async () => {
    await getData();
    let currentKey = '';
    let node = treeData.value;
    let level = 1;
    while (level < 3) {
        if (node.length > 0) {
            node = node[0].children || [];
        }
        level++;
    }
    currentKey = node[0]?.id as string;
    if (currentKey) {
        myProductTree.value?.setCurrentKey(currentKey);
    }
};

onMounted(() => {
    init();
});
</script>

<style scoped>
.tree-box {
    width: 300px;
}
.top {
    width: 100%;
    margin-bottom: 24px;
    gap: 8px;
}
.search-input:deep(.el-input-group__append) {
    padding: 0 12px;
}
.icon-button {
    width: 32px;
}
.icon-button + .el-button {
    margin-left: 0px;
}
</style>
